package com.xuecheng.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xuecheng.ucenter.exception.XueChengPlusException;
import com.xuecheng.ucenter.feignclient.CheckCodeClient;
import com.xuecheng.ucenter.mapper.Iuser;
import com.xuecheng.ucenter.mapper.UserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.po.User;
import com.xuecheng.ucenter.model.po.Users;
import com.xuecheng.ucenter.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author Mr.M
 * @version 1.0
 * @description 账号名密码方式
 * @date 2023/2/24 11:56
 */
@Service("password_authservice")
public class PasswordAuthServiceImpl implements AuthService {



 @Autowired
 Iuser usera;

 @Autowired
 PasswordEncoder passwordEncoder;

 @Autowired
 CheckCodeClient checkCodeClient;

 @Autowired
 UserMapper userMapper;

 @Override
 public Users execute(AuthParamsDto authParamsDto) {
  //账号
  String username = authParamsDto.getUsername();
  //拿 到用户输入的密码
  String passwordForm = authParamsDto.getPassword();

  //输入的验证码
  String checkcode = authParamsDto.getCheckcode();
  //验证码对应的key
  String checkcodekey = authParamsDto.getCheckcodekey();

  if (username == null || username.equals("")||passwordForm == null || passwordForm.equals(""))  {
   throw new XueChengPlusException("请输入账号或者密码");
  }



  //账号是否存在
//  QueryWrapper<User> wrapper = new QueryWrapper<>();
//  wrapper.eq("username",username);
////  List<User> users = usera.selectList(wrapper);
//  User user = usera.selectOne(wrapper);
//  System.out.println(user);

  //根据username账号查询数据库
//  XcUser xcUser = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername, username));

  //查询到用户不存在，要返回null即可，spring security框架抛出异常用户不存在
  Users user = userMapper.selectUserById(username);
  if(user==null){
   throw new RuntimeException("账号不存在");
  }

  //验证密码是否正确
  //如果查到了用户拿到正确的密码
  String passwordDb = user.getPassword();

  //校验密码
  boolean matches = passwordEncoder.matches(passwordForm, passwordDb);
  if(!matches){
//   throw new UsernameNotFoundException("账号不存在");
   throw new XueChengPlusException("账号或密码错误");
//   throw new RuntimeException("账号或密码错误");
  }
//  XcUserExt xcUserExt = new XcUserExt();
//  BeanUtils.copyProperties(xcUser,xcUserExt);

  return user;
 }
}
